import { Context } from 'koa';
import commentService from '../services/comment.service';

/**
 * 获取评论列表
 * @param ctx Koa上下文
 */
export const getComments = async (ctx: Context) => {
  try {
    const { 
      article_id, 
      user_id, 
      status, 
      parent_id, 
      keyword, 
      sort_by, 
      sort_order,
      page,
      limit,
      author_ip,
      author_email
    } = ctx.query;

    const params = {
      article_id: article_id as string,
      user_id: user_id as string,
      status: status as 'pending' | 'approved' | 'rejected',
      parent_id: parent_id as string,
      keyword: keyword as string,
      sort_by: sort_by as string,
      sort_order: sort_order as 'ASC' | 'DESC',
      page: page ? parseInt(page as string) : undefined,
      limit: limit ? parseInt(limit as string) : undefined,
      author_ip: author_ip as string,
      author_email: author_email as string,
    };

    const result = await commentService.getComments(params);
    
    ctx.body = {
      code: 200,
      data: result,
      message: '获取评论列表成功',
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: `获取评论列表失败: ${error.message}`,
    };
  }
};

/**
 * 获取文章评论树
 * @param ctx Koa上下文
 */
export const getArticleCommentTree = async (ctx: Context) => {
  try {
    const { article_id } = ctx.params;
    const { only_approved } = ctx.query;
    
    const onlyApproved = only_approved !== 'false'; // 默认为true
    
    const commentTree = await commentService.getArticleCommentTree(article_id, onlyApproved);
    
    ctx.body = {
      code: 200,
      data: commentTree,
      message: '获取文章评论树成功',
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: `获取文章评论树失败: ${error.message}`,
    };
  }
};

/**
 * 获取评论详情
 * @param ctx Koa上下文
 */
export const getCommentById = async (ctx: Context) => {
  try {
    const { id } = ctx.params;
    
    const comment = await commentService.getCommentById(id);
    
    ctx.body = {
      code: 200,
      data: comment,
      message: '获取评论详情成功',
    };
  } catch (error: any) {
    ctx.status = 404;
    ctx.body = {
      code: 404,
      message: `获取评论详情失败: ${error.message}`,
    };
  }
};

/**
 * 创建评论
 * @param ctx Koa上下文
 */
export const createComment = async (ctx: Context) => {
  try {
    const {
      content,
      article_id,
      user_id,
      parent_id,
      author_name,
      author_email,
      status,
    } = ctx.request.body;
    
    // 验证必填字段
    if (!content) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '评论内容不能为空',
      };
      return;
    }
    
    if (!article_id) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '文章ID不能为空',
      };
      return;
    }
    
    // 获取客户端IP和User-Agent
    const author_ip = ctx.request.ip;
    const author_user_agent = ctx.request.headers['user-agent'];
    
    const result = await commentService.createComment({
      content,
      article_id,
      user_id,
      parent_id,
      author_name,
      author_email,
      author_ip,
      author_user_agent,
      status,
    });
    
    ctx.status = 201;
    ctx.body = {
      code: 201,
      data: result,
      message: '创建评论成功',
    };
  } catch (error: any) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: `创建评论失败: ${error.message}`,
    };
  }
};

/**
 * 更新评论
 * @param ctx Koa上下文
 */
export const updateComment = async (ctx: Context) => {
  try {
    const { id } = ctx.params;
    const {
      content,
      status,
      reject_reason,
      is_pinned,
      is_hidden,
    } = ctx.request.body;
    
    // 获取当前用户ID作为审核人ID
    const reviewerId = ctx.state.user?.id;
    
    const comment = await commentService.updateComment(id, {
      content,
      status,
      reject_reason,
      is_pinned,
      is_hidden,
    }, reviewerId);
    
    ctx.body = {
      code: 200,
      data: comment,
      message: '更新评论成功',
    };
  } catch (error: any) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: `更新评论失败: ${error.message}`,
    };
  }
};

/**
 * 批量更新评论状态
 * @param ctx Koa上下文
 */
export const updateCommentsStatus = async (ctx: Context) => {
  try {
    const {
      ids,
      status,
      reject_reason,
    } = ctx.request.body;
    
    if (!Array.isArray(ids) || ids.length === 0) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '请选择要更新的评论',
      };
      return;
    }
    
    if (!['pending', 'approved', 'rejected'].includes(status)) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '无效的评论状态',
      };
      return;
    }
    
    // 获取当前用户ID作为审核人ID
    const reviewerId = ctx.state.user?.id;
    
    const result = await commentService.updateCommentsStatus(
      ids,
      status,
      reviewerId,
      reject_reason
    );
    
    ctx.body = {
      code: 200,
      data: result,
      message: result.message,
    };
  } catch (error: any) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: `批量更新评论状态失败: ${error.message}`,
    };
  }
};

/**
 * 删除评论
 * @param ctx Koa上下文
 */
export const deleteComment = async (ctx: Context) => {
  try {
    const { id } = ctx.params;
    
    const result = await commentService.deleteComment(id);
    
    ctx.body = {
      code: 200,
      data: result,
      message: result.message,
    };
  } catch (error: any) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: `删除评论失败: ${error.message}`,
    };
  }
};

/**
 * 批量删除评论
 * @param ctx Koa上下文
 */
export const deleteCommentsBatch = async (ctx: Context) => {
  try {
    const { ids } = ctx.request.body;
    
    if (!Array.isArray(ids) || ids.length === 0) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '请选择要删除的评论',
      };
      return;
    }
    
    const result = await commentService.deleteCommentsBatch(ids);
    
    ctx.body = {
      code: 200,
      data: result,
      message: result.message,
    };
  } catch (error: any) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: `批量删除评论失败: ${error.message}`,
    };
  }
};

/**
 * 获取IP黑名单
 * @param ctx Koa上下文
 */
export const getIPBlacklist = async (ctx: Context) => {
  try {
    const blacklist = await commentService.getIPBlacklist();
    
    ctx.body = {
      code: 200,
      data: blacklist,
      message: '获取IP黑名单成功',
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: `获取IP黑名单失败: ${error.message}`,
    };
  }
};

/**
 * 添加IP到黑名单
 * @param ctx Koa上下文
 */
export const addIPToBlacklist = async (ctx: Context) => {
  try {
    const { ip } = ctx.request.body;
    
    if (!ip) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: 'IP地址不能为空',
      };
      return;
    }
    
    const result = await commentService.addIPToBlacklist(ip);
    
    ctx.body = {
      code: 200,
      data: result,
      message: result.message,
    };
  } catch (error: any) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: `添加IP到黑名单失败: ${error.message}`,
    };
  }
}; 